package en.edu.zxj.mq.mqserver;

import en.edu.zxj.mq.common.*;
import en.edu.zxj.mq.common.util.BinaryUtils;
import en.edu.zxj.mq.mqserver.core.BasicProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description：这个 BrokerServer 就是 消息队列 本体服务器, 本质就是一个 TCP 的服务器
 *
 * @author: zxj
 * @date: 2024-03-05
 * @time: 22:59:24
 */
@Data
@Slf4j
public class BrokerServer {
    // 当前程序只考虑一个虚拟主机的情况
    private VirtualHost virtualHost = new VirtualHost("default-virtualHost");
    // 使用这个 哈希表, 表示当前的所有会话(也就是说有哪些客户端正在和服务器进行通信)
    // key 为 channelId, value 为 channel 对应的 socket 对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();

    private ServerSocket serverSocket;
    // 引入一个线程池, 来处理多个客户端的需求
    private ExecutorService executorService;
    // 引入一个 boolean 变量控制服务器是否继续运行
    private volatile boolean runnable = true;


    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    // begin: 单纯的 TCP 服务器模板
    public void start() {
        log.info("[BrokerServer] 服务器开始启动");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                // 把这个处理连接的逻辑对给线程池
                executorService.submit(() -> {
                    // 处理连接的统一方法
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            log.info("[BrokerServer] 服务器停止运行!");
        } catch (IOException e) {
            log.error("[BrokerServer] 服务器出现异常!");
            e.printStackTrace();
        }
    }

    /**
     * @description: 一般来说, 停止服务器, 都是 kill 对应的进程就可以了
     * 此处还是搞一个单独的停止方法, 主要是用于后续的单元测试
     **/
    public void stop() throws IOException {
        runnable = false;
        // 把线程池中的人物都放弃了, 让线程都销毁
        executorService.shutdownNow();
        serverSocket.close();
    }
    // end: 单纯的 TCP 服务器模板


    /**
     * @description: 服务方法
     * 通过这个方法, 来处里一个客户端的连接
     * 在这个连接中, 可能会涉及到多个请求和响应
     **/
    private void processConnection(@NotNull Socket clientSocket) {
        // 获取服务对象的 输入输出 流
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要按照特定的格式来读取并解析, 此时就需要用到 DataInputStream 和 DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream); DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                // 循环进行服务, 保持连接, 以便处理多个请求
                while (true) {
                    // 1. 读取请求并解析
                    Request request = readRequest(dataInputStream);
                    log.info("接收到[client: {} : {}] 请求: {}",clientSocket.getInetAddress(),clientSocket.getPort(),request);
                    // 2. 根据请求计算响应
                    Response response = process(request, clientSocket);
                    log.info("响应给[client: {} : {}] 数据: {}",clientSocket.getInetAddress(),clientSocket.getPort(),response);
                    // 3. 把响应写回给客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            log.info("connection 关闭! 客户端地址: {} : {}", clientSocket.getInetAddress(), clientSocket.getPort());
        } catch (IOException | MqException | ClassNotFoundException e) {
            log.error("connection 出现异常 e: {}", e.toString());
            e.printStackTrace();
        } finally {
            try {
                // 当连接处理完了, 一定要关闭 socket
                clientSocket.close();
                // 一个 TCP 连接中, 可能包含多个 channel, 需要把当前这个 socket 对应的所有 channel 也顺便清理掉
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @description: 反序列化请求消息
     **/
    private @NotNull Request readRequest(@NotNull DataInputStream dataInputStream) throws IOException, MqException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new MqException("读取请求格式出错");
        }
        request.setPayload(payload);
        return request;
    }

    /**
     * @description: 将 Response 对象中的内容先后写入 dataOutputStream 中
     **/
    private void writeResponse(@NotNull DataOutputStream dataOutputStream, Response response) throws IOException {
        log.info("{writeResponse}: 即将发送响应为: {}",response);
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        // 刷新缓冲区十分重要
        dataOutputStream.flush();
    }


    /**
     * @description: 依据 request 中的信息, 执行相关方法, 并构造 Response 对象返回
     **/
    private @NotNull Response process(@NotNull Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1. 把 request 中的 payload 做一个初步的解析, 让父类来接受
        BasicArguments basicArguments = (BasicArguments) BinaryUtils.fromBytes(request.getPayload());
        log.info("request 中 payload 解析结果:  rid = {}, channelId = {}", basicArguments.getRid(),basicArguments.getChannelId());
        // 2. 根据 type 的值, 来近一步来区分这一次请求时要干啥的
        boolean ok = true; // 各个方法的返回结果基本都是 boolean
        if (request.getType() == 0x1) {
            // 创建 channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            log.info("创建 channel 完成! channelId: {}", basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 销毁 channel
            sessions.remove(basicArguments.getChannelId());
            log.info("销毁 channel 完成! channelId: {}", basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 创建交换机, 此时的 payload 就是 ExchangeDeclareArguments 对象了
            ExchangeDeclareArguments exchangeDeclareArguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(exchangeDeclareArguments.getExchangeName(), exchangeDeclareArguments.getExchangeType(), exchangeDeclareArguments.getDurable(), exchangeDeclareArguments.getAutoDelete(), exchangeDeclareArguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 销毁交换机
            ExchangeDeleteArguments exchangeDeleteArguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(exchangeDeleteArguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建队列
            QueueDeclareArguments queueDeclareArguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(queueDeclareArguments.getQueueName(), queueDeclareArguments.isDurable(), queueDeclareArguments.isExclusive(), queueDeclareArguments.isAutoDelete(), queueDeclareArguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 销毁队列
            QueueDeleteArguments queueDeleteArguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(queueDeleteArguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 创建绑定
            QueueBindArguments queueBindArguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(queueBindArguments.getQueueName(), queueBindArguments.getExchangeName(), queueBindArguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 删除绑定
            QueueUnBindArguments queueUnBindArguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnBind(queueUnBindArguments.getQueueName(), queueUnBindArguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发布消息
            BasicPublishArguments basicPublishArguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(basicPublishArguments.getExchangeName(), basicPublishArguments.getRoutingKey(), basicPublishArguments.getBasicProperties(), basicPublishArguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArguments basicConsumeArguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(basicConsumeArguments.getConsumerTag(), basicConsumeArguments.getQueueName(), basicConsumeArguments.isAutoAck(), new Consumer() {
                /**
                 * 这个回调函数要做的工作, 就是把服务收到消息直接推送会给对应的消费者客户端即可, 在客户端进行对消息的消费
                 **/
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    // 先知道当前这个收到的消息, 要发给哪个客户端
                    // 此处 consumerTag, 其实就是 channelId (这里是规定的, 客户端填写该字段的时候, 就是以 channelId 来填写的),
                    // 根据 channelId 去 sessions 中查询, 就可以得到对应的 socket 对象, 就可以往里面发送数据了
                    // 1. 根据 channelId 找到 socket 对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!");
                    }

                    // 2. 构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setRid(""); // 由于这里只有响应, 没有请求, 不需要去对应, rid 暂时不需要
                    subScribeReturns.setOk(true);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryUtils.toBytes(subScribeReturns);

                    Response response = new Response();
                    // 0xc 表示服务器给消费者客户端推送消息数据
                    response.setType(0xc);
                    // response 的 payload 就是一个 SubScribeReturns
                    response.setLength(payload.length);
                    response.setPayload(payload);

                    // 3. 把数据写回给客户端
                    //      注意! 此处的 dataOutputStream 不能close!
                    //      如果把 dataOutputStream 关闭, 就会直接把 clientSocket 里的 OutputStream 也关闭了
                    //      此时就无法继续往 socket 中写入后续数据了
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response);

                }
            });
        } else if (request.getType() == 0xb) {
            // 确认应答, 消费者确认收到消息
            BasicAckArguments basicAckArguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(basicAckArguments.getQueueName(), basicAckArguments.getMessageId());
        } else {
            // 当前的 type 是非法的
            throw new MqException("未知的 type: " + request.getType());
        }

        // 3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryUtils.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);

        log.info("构造响应完成: {}", response);

        return response;
    }


    /**
     * @description: 用户关闭连接后, 清理对应的 channel 资源
     * 需要注意的是 迭代器失效的问题
     **/
    private void clearClosedSession(Socket clientSocket) {
        // 这里要做的事情, 主要就是遍历上述 sessions hash 表, 把该关闭的 socket 对应的键值对, 统统删除
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                // 不能在这里直接删除!!
                // 这属于使用集合类的一个大忌 -- 一边遍历, 一边删除!
                // sessions.remove(entry.getKey());
                toDeleteChannelId.add(entry.getKey());
            }
        }

        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }

        log.info("清理 session 完成! 被清理的 channelId: {}", toDeleteChannelId);
    }

}
